<template>
  <view class="leave-form-page">
    <!-- 表头 -->
    <view class="form-header">
      <view class="nav-left" @click="goBack">
        <u-icon name="arrow-left" color="#1f2a56" size="24"></u-icon>
      </view>
      <view class="title-block">
        <text class="title">{{ templateName || '请假申请' }}</text>
        <text class="subtitle">{{ modeLabel }}</text>
      </view>
    </view>

    <!-- 内容 -->
    <view class="form-wrapper">
      <component
        v-if="currentComponent"
        :is="currentComponent"
        ref="formRef"
        :template-id="templateId"
        :template-name="templateName"
        :mode="mode"
        :leave-id="leaveId"
        @save-success="handleSaveSuccess"
        @submit-success="handleSubmitSuccess"
      />
    </view>

    <!-- 编辑/新建模式的操作按钮 -->
    <view class="actions" v-if="mode !== 'view'">
      <u-button type="info" plain @click="handleSaveDraft" :loading="submitting">
        保存草稿
      </u-button>
      <!-- <u-button type="primary" :loading="submitting" @click="handleSubmit">提交审批</u-button> -->
    </view>

    <!-- 查看模式的审批按钮 -->
    <view class="actions" v-if="mode === 'view' && showApprovalButton">
      <u-button type="success" @click="handleApprove">去审批</u-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'
import InternalApplication from '@/pages/leave/components/InternalApplication.vue'
import LeaveApplication from '@/pages/leave/components/LeaveApplication.vue'

type FormMode = 'create' | 'edit' | 'view'

const templateId = ref<number | null>(null)
const templateCode = ref('leave_report')
const templateName = ref('请假申请')
const mode = ref<FormMode>('create')
const leaveId = ref<number | null>(null)
const submitting = ref(false)
const formRef = ref<any>(null)
const showApprovalButton = ref(false) // 是否显示审批按钮

const currentComponent = computed(() => {
  if (templateCode.value === 'outing_report') {
    return InternalApplication
  }
  return LeaveApplication
})

const modeLabel = computed(() => {
  switch (mode.value) {
    case 'create':
      return '新建申请'
    case 'edit':
      return '编辑申请'
    case 'view':
      return '查看详情'
    default:
      return ''
  }
})

const parseNumber = (value?: string) => {
  if (!value && value !== '0') return null
  const num = Number(value)
  return Number.isNaN(num) ? null : num
}

onLoad((options) => {
  templateId.value = parseNumber(options?.templateId as string)
  templateCode.value = (options?.templateCode as string) || 'leave_report'

  // 解码 templateName，确保中文字符正确显示
  let decodedTemplateName = (options?.templateName as string) || '请假申请'
  try {
    // 如果包含 URL 编码字符，进行解码
    if (decodedTemplateName.includes('%')) {
      decodedTemplateName = decodeURIComponent(decodedTemplateName)
    }
  } catch (e) {
    // 解码失败时使用原始值
  }
  templateName.value = decodedTemplateName

  // 支持 id 和 leaveId 两种参数名
  leaveId.value = parseNumber(options?.id as string) || parseNumber(options?.leaveId as string)
  mode.value = ((options?.mode as FormMode) || 'create') as FormMode

  // 如果是从待审批列表进入查看模式，显示审批按钮
  showApprovalButton.value = options?.showApproval === 'true' || options?.showApproval === '1'
})

onUnload(() => {
  // 离开页面刷新列表
  uni.$emit('leave:reload')
})

const handleSaveDraft = async () => {
  if (!formRef.value) {
    uni.showToast({ title: '表单未加载', icon: 'none' })
    return
  }
  if (!formRef.value.handleSaveDraft) {
    uni.showToast({ title: '保存方法不可用', icon: 'none' })
    return
  }
  submitting.value = true
  try {
    await formRef.value.handleSaveDraft()
  } catch (error: any) {
    uni.showToast({ title: error?.message || '保存失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) {
    uni.showToast({ title: '表单未加载', icon: 'none' })
    return
  }
  if (!formRef.value.handleSubmit) {
    uni.showToast({ title: '提交方法不可用', icon: 'none' })
    return
  }
  submitting.value = true
  try {
    await formRef.value.handleSubmit()
  } catch (error: any) {
    uni.showToast({ title: error?.message || '提交失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

const handleSaveSuccess = () => {
  // 保存成功后返回上一页
  setTimeout(() => {
    // const pages = getCurrentPages()
    // if (pages.length > 1) {
    //   uni.navigateBack({ delta: 1 })
    // } else {
    // }
    uni.reLaunch({ url: '/pages/leave/applications/index' })
  }, 1500)
}

const handleSubmitSuccess = () => {
  // 提交成功后返回上一页
  setTimeout(() => {
    // const pages = getCurrentPages()
    // if (pages.length > 1) {
    //   uni.navigateBack({ delta: 1 })
    // } else {
    // }
    uni.reLaunch({ url: '/pages/leave/applications/index' })
  }, 1500)
}

const handleApprove = () => {
  // 返回上一页并触发审批
  uni.navigateBack({
    delta: 1,
    success: () => {
      // 通过事件通知待审批页面打开审批弹窗
      uni.$emit('leave:approve', leaveId.value)
    },
  })
}

const goBack = () => {
  const pages = getCurrentPages()
  // 如果页面栈只有1个页面，说明无法返回，直接跳转到首页
  if (pages.length <= 1) {
    uni.reLaunch({
      url: '/pages/leave/index',
    })
  } else {
    // 有多个页面，执行返回操作
    uni.navigateBack({
      delta: 1,
    })
  }
}
</script>

<style scoped lang="scss">
.leave-form-page {
  height: 100vh;
  padding: 44px 32rpx 20rpx;
  box-sizing: border-box;
  background: linear-gradient(180deg, #eef2ff 0%, #f7f8fc 60%, #ffffff 100%);
  background: #eef2ff;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 28rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid rgba(223, 228, 244, 0.9);

  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    cursor: pointer;
    margin-right: 20rpx;
  }

  .title-block {
    display: flex;
    flex-direction: column;
    flex: 1;
    min-width: 0;

    .title {
      font-size: 36rpx;
      font-weight: 700;
      color: #1f2a56;
    }

    .subtitle {
      font-size: 26rpx;
      color: #8b90a5;
      margin-top: 8rpx;
    }
  }

  .actions {
    display: flex;
    justify-content: flex-end;
    flex-shrink: 0;
    flex-wrap: wrap;

    :deep(.u-button) {
      width: 100%;
      height: 64rpx;
      font-size: 28rpx;
      margin-left: 16rpx;

      &:first-child {
        margin-left: 0;
      }
    }
  }
}

.form-wrapper {
  width: 100%;
  position: relative;
  flex: 1;
  overflow: auto;
}

.actions {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;

  :deep(.u-button) {
    flex: 1;
    width: 100%;
    height: 72rpx;
    font-size: 30rpx;
    margin-left: 32rpx;
    margin-right: 0;

    &:after {
      display: none;
    }

    &:first-child {
      margin-left: 0;
    }
  }
}
</style>
